package com.prizedraw.prize_draw.security;

import cn.hutool.core.util.StrUtil;
import com.prizedraw.prize_draw.entity.SysUser;
import com.prizedraw.prize_draw.service.SysUserService;
import com.prizedraw.prize_draw.util.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class JwtAuthenticationFilter extends BasicAuthenticationFilter {
    @Autowired
    JwtUtil jwtUtil;

    @Autowired
    SysUserService sysUserService;

    @Autowired
    UserDetailsServiceImpl userDetailsService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        String jwt = request.getHeader(jwtUtil.getHeader());
        //不带jwt token就不走此过滤器验证token，让它去匿名访问过滤器，
        //看是否是白名单中的url，如果不是白名单中的url，就会抛异常，去登录页
        if(StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return;
        }
        Claims claims = jwtUtil.getClaimByToken(jwt);
        if (claims == null){
            throw new JwtException("token 异常");
        }
        if (jwtUtil.isTokenExpired(claims)){
            throw new JwtException("token 已过期");
        }
        String userId = claims.getSubject();

        //获取用户的权限等信息
        SysUser user = sysUserService.getByUserId(userId);
        UsernamePasswordAuthenticationToken token
                = new UsernamePasswordAuthenticationToken(userId, null, userDetailsService.getUserAuthority(user.getId()));
        SecurityContextHolder.getContext().setAuthentication(token);

        chain.doFilter(request, response);
    }
}
